package com.linzelin.service;

import com.linzelin.dao.UserMapper;
import com.linzelin.po.Role;
import com.linzelin.po.SysUser;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.ArrayList;
import java.util.List;

public class UserServiceImpl implements UserService {
    private UserMapper mapper;

    private BCryptPasswordEncoder passwordEncoder;
    /*这个就需要布置在添加用户的方法里了*/

    public void setMapper(UserMapper mapper) {
        this.mapper = mapper;
    }

    public void setPasswordEncoder(BCryptPasswordEncoder passwordEncoder) {
        //为加密类动态赋值
        this.passwordEncoder = passwordEncoder;
    }

    public int addUser(SysUser user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        //这样就加密了
        return 0;
        //这里应该执行调用数据库的,这里就不搞了,直接复制加密后的密文修改i数据集
    }

    @Override
    public SysUser selectUser(String username, String password) {
        return mapper.selectUser(username, password);
    }

    @Override
    public SysUser selectUserByUsername(String username) {
        return mapper.selectUserByUsername(username);
    }

    /**
     * @param username 这里就是传入对应的用户名,就是用户在浏览器输入的用户名
     * @return SpringSecurity自己的一个用户对象
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //注意这里是需要先使用自己的用户数据库查询出对应的用户账号,转化为SpringSecurity对应的用户对象
        try {
            SysUser sysUser = mapper.selectUserByUsername(username);
            if (sysUser == null) {
                return null;
            }
            List<SimpleGrantedAuthority> authorities = new ArrayList<>();
            //这里就是添加一个对应的角色到这里的list集合中了
            List<Role> roleList = sysUser.getRoleList();
            for (Role role : roleList) {
                authorities.add(new SimpleGrantedAuthority(role.getRoleName()));
            }
            //这里就是动态将对应的角色导入到这里面
            UserDetails userDetails = new User(sysUser.getUsername(), sysUser.getPassword()
                    , sysUser.getStatus() == 1,
                    true, true, true,
                    authorities);
            /*这里只验证这个用户是否能正常登录即可*/
            //{noop}后面的密码会被认为是原文
            //这里有一个安保措施,最后一个参数配置的就是对应的加密
            return userDetails;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
            //在SpringSecurity中如果返回的是null就代表认证失败
        }
    }

}
